<template>
  <div class="settings-management">
    <el-row :gutter="20">
      <!-- 营业设置 -->
      <el-col :span="12">
        <el-card shadow="hover" class="settings-card">
          <template #header>
            <div class="card-header">
              <span>营业设置</span>
              <el-tag :type="businessSettings.isOpen ? 'success' : 'danger'">
                {{ businessSettings.isOpen ? '营业中' : '已打烊' }}
              </el-tag>
            </div>
          </template>
          
          <el-form :model="businessSettings" label-width="120px">
            <el-form-item label="营业状态控制">
              <el-button
                :type="businessSettings.isOpen ? 'danger' : 'success'"
                @click="toggleBusinessStatus"
                :loading="statusChanging"
              >
                {{ businessSettings.isOpen ? '停止营业' : '开始营业' }}
              </el-button>
              <div class="setting-desc">
                {{ businessSettings.isOpen ? '当前正在接受新订单' : '当前暂停接受新订单' }}
              </div>
            </el-form-item>

            <el-form-item label="最大服务距离">
              <el-slider
                v-model="businessSettings.maxDistance"
                :min="1"
                :max="20"
                :step="0.5"
                :format-tooltip="formatDistanceTooltip"
                @change="handleSettingChange"
              />
              <div class="setting-desc">当前设置：{{ businessSettings.maxDistance }}公里</div>
            </el-form-item>

            <el-form-item label="配送费用设置">
              <div class="delivery-fee-section">
                <div class="fee-item">
                  <span class="fee-label">免费配送距离：</span>
                  <el-input-number
                    v-model="businessSettings.freeDeliveryDistance"
                    :min="0"
                    :max="10"
                    :step="0.5"
                    controls-position="right"
                    @change="handleSettingChange"
                  />
                  <span class="fee-unit">公里</span>
                </div>
                <div class="fee-item">
                  <span class="fee-label">超出距离配送费：</span>
                  <el-input-number
                    v-model="businessSettings.deliveryFeePerKm"
                    :min="0"
                    :max="20"
                    :step="0.5"
                    controls-position="right"
                    @change="handleSettingChange"
                  />
                  <span class="fee-unit">元/公里</span>
                </div>
                <div class="fee-example">
                  <el-icon><InfoFilled /></el-icon>
                  <span>
                    示例：{{ businessSettings.freeDeliveryDistance }}公里内免费配送，
                    超出部分按{{ businessSettings.deliveryFeePerKm }}元/公里收费
                  </span>
                </div>
              </div>
            </el-form-item>
            
            <el-form-item label="营业时间">
              <el-time-picker
                v-model="workingTimeRange"
                is-range
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                format="HH:mm"
                value-format="HH:mm"
                @change="handleWorkingTimeChange"
              />
              <div class="setting-desc">
                营业时间内的消息回复影响店铺评分，非营业时间不影响
              </div>
            </el-form-item>

            <el-form-item label="消息回复设置">
              <div class="message-settings">
                <div class="setting-item">
                  <span>营业时间内回复时限：</span>
                  <el-input-number
                    v-model="businessSettings.replyTimeLimit"
                    :min="1"
                    :max="60"
                    controls-position="right"
                  />
                  <span>分钟</span>
                </div>
                <div class="setting-desc">
                  超过此时限未回复将影响店铺综合分数和流量
                </div>
              </div>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
      
      <!-- 风控设置 -->
      <el-col :span="12">
        <el-card shadow="hover" class="settings-card">
          <template #header>
            <div class="card-header">
              <span>风控设置</span>
              <el-tag type="warning">服务质量监控</el-tag>
            </div>
          </template>

          <el-form :model="riskSettings" label-width="120px">
            <el-form-item label="退款率预警">
              <el-input-number
                v-model="riskSettings.refundRateThreshold"
                :min="5"
                :max="30"
                :step="1"
                controls-position="right"
                @change="handleSettingChange"
              />
              <span style="margin-left: 8px;">%</span>
              <div class="setting-desc">
                超过此比例将影响店铺排名和流量分配
              </div>
            </el-form-item>

            <el-form-item label="好评率预警">
              <el-input-number
                v-model="riskSettings.goodReviewThreshold"
                :min="60"
                :max="95"
                :step="1"
                controls-position="right"
                @change="handleSettingChange"
              />
              <span style="margin-left: 8px;">%</span>
              <div class="setting-desc">
                低于此比例将限制自动提现功能
              </div>
            </el-form-item>

            <el-form-item label="响应时间预警">
              <el-input-number
                v-model="riskSettings.responseTimeThreshold"
                :min="1"
                :max="10"
                :step="0.5"
                controls-position="right"
                @change="handleSettingChange"
              />
              <span style="margin-left: 8px;">分钟</span>
              <div class="setting-desc">
                超过此时间未响应将影响服务评分
              </div>
            </el-form-item>

            <el-form-item label="风控提醒">
              <el-switch
                v-model="riskSettings.enableRiskAlert"
                active-text="开启"
                inactive-text="关闭"
                @change="handleSettingChange"
              />
              <div class="setting-desc">
                开启后将实时监控并提醒风险指标
              </div>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 服务区域设置 -->
    <el-card shadow="hover" class="settings-card" style="margin-top: 20px;">
      <template #header>
        <div class="card-header">
          <span>服务区域设置</span>
          <el-button type="primary" size="small" @click="handleAddServiceArea">
            添加区域
          </el-button>
        </div>
      </template>
      
      <div class="service-areas">
        <div v-for="(area, index) in serviceAreas" :key="index" class="area-item">
          <div class="area-info">
            <div class="area-name">{{ area.name }}</div>
            <div class="area-desc">{{ area.description }}</div>
            <div class="area-range">服务半径：{{ area.radius }}公里</div>
          </div>
          <div class="area-actions">
            <el-button size="small" @click="editServiceArea(index)">编辑</el-button>
            <el-button size="small" type="danger" @click="removeServiceArea(index)">删除</el-button>
          </div>
        </div>
        
        <div v-if="serviceAreas.length === 0" class="empty-areas">
          <el-empty description="暂无服务区域，请添加服务区域" />
        </div>
      </div>
    </el-card>
    
    <!-- 通知设置 -->
    <el-card shadow="hover" class="settings-card" style="margin-top: 20px;">
      <template #header>
        <span>通知设置</span>
      </template>
      
      <el-form :model="notificationSettings" label-width="120px">
        <el-form-item label="新订单通知">
          <el-switch
            v-model="notificationSettings.newOrder"
            active-text="开启"
            inactive-text="关闭"
            @change="handleSettingChange"
          />
        </el-form-item>
        
        <el-form-item label="客户评价通知">
          <el-switch
            v-model="notificationSettings.customerReview"
            active-text="开启"
            inactive-text="关闭"
            @change="handleSettingChange"
          />
        </el-form-item>
        
        <el-form-item label="财务变动通知">
          <el-switch
            v-model="notificationSettings.financeChange"
            active-text="开启"
            inactive-text="关闭"
            @change="handleSettingChange"
          />
        </el-form-item>
        
        <el-form-item label="系统维护通知">
          <el-switch
            v-model="notificationSettings.systemMaintenance"
            active-text="开启"
            inactive-text="关闭"
            @change="handleSettingChange"
          />
        </el-form-item>
        
        <el-form-item label="通知方式">
          <el-checkbox-group v-model="notificationSettings.methods" @change="handleSettingChange">
            <el-checkbox label="app">APP推送</el-checkbox>
            <el-checkbox label="sms">短信通知</el-checkbox>
            <el-checkbox label="email">邮件通知</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 界面设置 -->
    <el-card shadow="hover" class="settings-card" style="margin-top: 20px;">
      <template #header>
        <div class="card-header">
          <span>界面设置</span>
          <el-tag :type="interfaceSettings.theme === 'dark' ? 'info' : 'success'">
            {{ interfaceSettings.theme === 'dark' ? '夜间模式' : '白天模式' }}
          </el-tag>
        </div>
      </template>

      <el-form :model="interfaceSettings" label-width="120px">
        <el-form-item label="主题模式">
          <div class="theme-selector">
            <div class="theme-options">
              <div
                class="theme-option"
                :class="{ active: interfaceSettings.theme === 'light' }"
                @click="setTheme('light')"
              >
                <div class="theme-preview light-preview">
                  <div class="preview-header"></div>
                  <div class="preview-content">
                    <div class="preview-sidebar"></div>
                    <div class="preview-main"></div>
                  </div>
                </div>
                <div class="theme-name">
                  <el-icon><Sunny /></el-icon>
                  <span>白天模式</span>
                </div>
              </div>

              <div
                class="theme-option"
                :class="{ active: interfaceSettings.theme === 'dark' }"
                @click="setTheme('dark')"
              >
                <div class="theme-preview dark-preview">
                  <div class="preview-header"></div>
                  <div class="preview-content">
                    <div class="preview-sidebar"></div>
                    <div class="preview-main"></div>
                  </div>
                </div>
                <div class="theme-name">
                  <el-icon><Moon /></el-icon>
                  <span>夜间模式</span>
                </div>
              </div>

              <div
                class="theme-option"
                :class="{ active: interfaceSettings.theme === 'auto' }"
                @click="setTheme('auto')"
              >
                <div class="theme-preview auto-preview">
                  <div class="preview-header"></div>
                  <div class="preview-content">
                    <div class="preview-sidebar"></div>
                    <div class="preview-main"></div>
                  </div>
                </div>
                <div class="theme-name">
                  <el-icon><Monitor /></el-icon>
                  <span>跟随系统</span>
                </div>
              </div>
            </div>
            <div class="theme-description">
              <el-icon><InfoFilled /></el-icon>
              <span>
                {{ getThemeDescription() }}
              </span>
            </div>
          </div>
        </el-form-item>

        <el-form-item label="护眼设置">
          <div class="eye-protection-settings">
            <div class="setting-item">
              <el-switch
                v-model="interfaceSettings.eyeProtection"
                active-text="开启护眼模式"
                inactive-text="关闭护眼模式"
                @change="handleEyeProtectionChange"
              />
            </div>
            <div class="setting-desc">
              护眼模式会降低屏幕蓝光，减少眼部疲劳，适合长时间使用
            </div>

            <div v-if="interfaceSettings.eyeProtection" class="eye-protection-options">
              <div class="option-item">
                <span class="option-label">护眼强度：</span>
                <el-slider
                  v-model="interfaceSettings.eyeProtectionLevel"
                  :min="1"
                  :max="5"
                  :step="1"
                  :format-tooltip="formatEyeProtectionTooltip"
                  @change="handleEyeProtectionLevelChange"
                  style="width: 200px;"
                />
                <span class="option-value">{{ getEyeProtectionLevelText() }}</span>
              </div>

              <div class="option-item">
                <span class="option-label">自动护眼：</span>
                <el-switch
                  v-model="interfaceSettings.autoEyeProtection"
                  active-text="开启"
                  inactive-text="关闭"
                  @change="handleAutoEyeProtectionChange"
                />
                <span class="option-desc">晚上18:00-次日8:00自动开启护眼模式</span>
              </div>
            </div>
          </div>
        </el-form-item>


      </el-form>
    </el-card>



    <!-- 保存按钮 -->
    <div class="save-actions">
      <el-button type="primary" size="large" @click="saveAllSettings" :loading="saving">
        保存所有设置
      </el-button>
      <el-button size="large" @click="resetAllSettings">
        重置为默认
      </el-button>
    </div>
    
    <!-- 服务区域编辑对话框 -->
    <el-dialog
      v-model="areaDialogVisible"
      :title="editingAreaIndex === -1 ? '添加服务区域' : '编辑服务区域'"
      width="500px"
      @close="resetAreaForm"
    >
      <el-form
        ref="areaFormRef"
        :model="areaForm"
        :rules="areaRules"
        label-width="100px"
      >
        <el-form-item label="区域名称" prop="name">
          <el-input v-model="areaForm.name" placeholder="请输入区域名称" />
        </el-form-item>
        <el-form-item label="区域描述" prop="description">
          <el-input
            v-model="areaForm.description"
            type="textarea"
            placeholder="请输入区域描述"
            :rows="3"
          />
        </el-form-item>
        <el-form-item label="服务半径" prop="radius">
          <el-input-number
            v-model="areaForm.radius"
            :min="1"
            :max="50"
            :step="0.5"
            controls-position="right"
          />
          <span style="margin-left: 10px;">公里</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="areaDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveServiceArea">确定</el-button>
        </span>
      </template>
    </el-dialog>


  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  InfoFilled,
  Sunny,
  Moon,
  Monitor
} from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import {
  getMerchantSettings,
  updateMerchantSettings,
  getBusinessSettings,
  updateBusinessSettings,
  getRiskSettings,
  updateRiskSettings,
  getNotificationSettings,
  updateNotificationSettings,
  getInterfaceSettings,
  updateInterfaceSettings,
  getServiceAreas,
  addServiceArea,
  updateServiceArea,
  deleteServiceArea,
  resetSettingsToDefault,
  validateSettings,
  THEME_MODES,
  THEME_MODE_TEXT,

  EYE_PROTECTION_LEVELS,
  EYE_PROTECTION_LEVEL_TEXT,
  getThemeDescription,
  getEyeProtectionLevelDescription,
  validateWorkingHours,
  validateServiceArea,
  calculateDeliveryFee
} from '@/api/settings'

const userStore = useUserStore()

// 响应式数据
const saving = ref(false)
const areaDialogVisible = ref(false)
const editingAreaIndex = ref(-1)
const areaFormRef = ref()

// 营业设置
const businessSettings = reactive({
  isOpen: false,
  maxDistance: 5,
  freeDeliveryDistance: 3, // 免费配送距离
  deliveryFeePerKm: 2, // 超出距离配送费
  replyTimeLimit: 5 // 消息回复时限（分钟）
})

const statusChanging = ref(false)

// 风控设置
const riskSettings = reactive({
  refundRateThreshold: 15,
  goodReviewThreshold: 80,
  responseTimeThreshold: 3,
  enableRiskAlert: true
})

// 通知设置
const notificationSettings = reactive({
  newOrder: true,
  customerReview: true,
  financeChange: true,
  systemMaintenance: true,
  methods: ['app', 'sms']
})

// 界面设置
const interfaceSettings = reactive({
  theme: THEME_MODES.LIGHT,
  eyeProtection: false,
  eyeProtectionLevel: 3, // 1-5
  autoEyeProtection: false
})

// 服务区域
const serviceAreas = ref([])

// 服务区域表单
const areaForm = reactive({
  name: '',
  description: '',
  radius: 3
})

// 服务区域表单验证规则
const areaRules = {
  name: [
    { required: true, message: '请输入区域名称', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入区域描述', trigger: 'blur' }
  ],
  radius: [
    { required: true, message: '请输入服务半径', trigger: 'blur' }
  ]
}



// 获取营业设置数据
const getBusinessSettingsData = async () => {
  try {
    const response = await getBusinessSettings()
    if (response.code === 200) {
      const data = response.data
      Object.assign(businessSettings, {
        isOpen: data.isOpen || false,
        maxDistance: data.maxDistance || 5,
        freeDeliveryDistance: data.freeDeliveryDistance || 3,
        deliveryFeePerKm: data.deliveryFeePerKm || 2,
        replyTimeLimit: data.replyTimeLimit || 5
      })

      if (data.workingHours) {
        workingTimeRange.value = data.workingHours
      }
    } else {
      throw new Error(response.message || '获取营业设置失败')
    }
  } catch (error) {
    console.error('获取营业设置失败:', error)
    ElMessage.error(error.message || '获取营业设置失败')
  }
}

// 获取风控设置数据
const getRiskSettingsData = async () => {
  try {
    const response = await getRiskSettings()
    if (response.code === 200) {
      const data = response.data
      Object.assign(riskSettings, {
        refundRateThreshold: data.refundRateThreshold || 15,
        goodReviewThreshold: data.goodReviewThreshold || 80,
        responseTimeThreshold: data.responseTimeThreshold || 3,
        enableRiskAlert: data.enableRiskAlert !== undefined ? data.enableRiskAlert : true
      })
    } else {
      throw new Error(response.message || '获取风控设置失败')
    }
  } catch (error) {
    console.error('获取风控设置失败:', error)
    ElMessage.error(error.message || '获取风控设置失败')
  }
}

// 获取通知设置数据
const getNotificationSettingsData = async () => {
  try {
    const response = await getNotificationSettings()
    if (response.code === 200) {
      const data = response.data
      Object.assign(notificationSettings, {
        newOrder: data.newOrder !== undefined ? data.newOrder : true,
        customerReview: data.customerReview !== undefined ? data.customerReview : true,
        financeChange: data.financeChange !== undefined ? data.financeChange : true,
        systemMaintenance: data.systemMaintenance !== undefined ? data.systemMaintenance : true,
        methods: data.methods || ['app', 'sms']
      })
    } else {
      throw new Error(response.message || '获取通知设置失败')
    }
  } catch (error) {
    console.error('获取通知设置失败:', error)
    ElMessage.error(error.message || '获取通知设置失败')
  }
}

// 获取界面设置数据
const getInterfaceSettingsData = async () => {
  try {
    const response = await getInterfaceSettings()
    if (response.code === 200) {
      const data = response.data
      Object.assign(interfaceSettings, {
        theme: data.theme || THEME_MODES.LIGHT,
        eyeProtection: data.eyeProtection || false,
        eyeProtectionLevel: data.eyeProtectionLevel || 3,
        autoEyeProtection: data.autoEyeProtection || false
      })
    } else {
      // 从本地存储获取界面设置
      const savedSettings = localStorage.getItem('merchant-interface-settings')
      if (savedSettings) {
        try {
          const parsed = JSON.parse(savedSettings)
          Object.assign(interfaceSettings, parsed)
        } catch (e) {
          console.warn('解析本地界面设置失败:', e)
        }
      }
    }
  } catch (error) {
    console.error('获取界面设置失败:', error)
    // 从本地存储获取界面设置
    const savedSettings = localStorage.getItem('merchant-interface-settings')
    if (savedSettings) {
      try {
        const parsed = JSON.parse(savedSettings)
        Object.assign(interfaceSettings, parsed)
      } catch (e) {
        console.warn('解析本地界面设置失败:', e)
      }
    }
  }
}

// 获取服务区域数据
const getServiceAreasData = async () => {
  try {
    const response = await getServiceAreas()
    if (response.code === 200) {
      // 确保 serviceAreas.value 是数组
      if (response.data && response.data.currentAreas) {
        serviceAreas.value = response.data.currentAreas || []
      } else if (Array.isArray(response.data)) {
        serviceAreas.value = response.data
      } else {
        serviceAreas.value = []
      }
    } else {
      throw new Error(response.message || '获取服务区域失败')
    }
  } catch (error) {
    console.error('获取服务区域失败:', error)
    serviceAreas.value = []
  }
}

// 计算属性
const workingTimeRange = computed({
  get() {
    return businessSettings.workingHours || ['08:00', '20:00']
  },
  set(value) {
    businessSettings.workingHours = value
  }
})

// 方法
const formatDistanceTooltip = (value) => {
  return `${value}公里`
}

const toggleBusinessStatus = async () => {
  try {
    const action = businessSettings.isOpen ? '停止营业' : '开始营业'
    await ElMessageBox.confirm(
      `确认${action}？${businessSettings.isOpen ? '停止后将不再接收新订单' : '开始后将正常接收订单'}`,
      '营业状态',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    statusChanging.value = true

    const newStatus = !businessSettings.isOpen
    const response = await updateBusinessSettings({
      ...businessSettings,
      isOpen: newStatus
    })

    if (response.code === 200) {
      businessSettings.isOpen = newStatus
      ElMessage.success(`已${action}`)
      handleSettingChange()
    } else {
      throw new Error(response.message || `${action}失败`)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('切换营业状态失败:', error)
      ElMessage.error(error.message || '操作失败')
    }
  } finally {
    statusChanging.value = false
  }
}



const handleWorkingTimeChange = async (value) => {
  if (value && value.length === 2) {
    const validation = validateWorkingHours(value[0], value[1])
    if (!validation.valid) {
      ElMessage.error(validation.message)
      return
    }

    try {
      const response = await updateBusinessSettings({
        ...businessSettings,
        workingHours: value
      })

      if (response.code === 200) {
        businessSettings.workingHours = value
        ElMessage.success(`工作时间已设置为 ${value[0]} - ${value[1]}`)
        handleSettingChange()
      } else {
        throw new Error(response.message || '更新工作时间失败')
      }
    } catch (error) {
      console.error('更新工作时间失败:', error)
      ElMessage.error(error.message || '更新工作时间失败')
    }
  }
}

const handleSettingChange = () => {
  // 标记设置已变更，可以在这里添加自动保存逻辑
  console.log('设置已变更')
}

// 主题设置方法
const setTheme = (theme) => {
  interfaceSettings.theme = theme
  applyTheme(theme)
  handleSettingChange()
  ElMessage.success(`已切换到${getThemeName(theme)}`)
}

const applyTheme = (theme) => {
  const root = document.documentElement

  if (theme === 'dark') {
    root.classList.add('dark-theme')
    root.classList.remove('light-theme')
  } else if (theme === 'light') {
    root.classList.add('light-theme')
    root.classList.remove('dark-theme')
  } else if (theme === 'auto') {
    // 跟随系统主题
    const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches
    if (prefersDark) {
      root.classList.add('dark-theme')
      root.classList.remove('light-theme')
    } else {
      root.classList.add('light-theme')
      root.classList.remove('dark-theme')
    }
  }
}

const getThemeName = (theme) => {
  const names = {
    light: '白天模式',
    dark: '夜间模式',
    auto: '跟随系统'
  }
  return names[theme] || '未知模式'
}



// 护眼设置方法
const handleEyeProtectionChange = (value) => {
  if (value) {
    applyEyeProtection()
    ElMessage.success('护眼模式已开启')
  } else {
    removeEyeProtection()
    ElMessage.success('护眼模式已关闭')
  }
  handleSettingChange()
}

const handleEyeProtectionLevelChange = (value) => {
  applyEyeProtection()
  ElMessage.success(`护眼强度已调整为${getEyeProtectionLevelText()}`)
  handleSettingChange()
}

const handleAutoEyeProtectionChange = (value) => {
  if (value) {
    setupAutoEyeProtection()
    ElMessage.success('自动护眼已开启，将在晚上18:00-次日8:00自动启用')
  } else {
    clearAutoEyeProtection()
    ElMessage.success('自动护眼已关闭')
  }
  handleSettingChange()
}

const applyEyeProtection = () => {
  const root = document.documentElement
  const level = interfaceSettings.eyeProtectionLevel

  // 根据护眼强度设置CSS变量
  const filterValue = `sepia(${level * 10}%) saturate(${100 - level * 5}%) brightness(${100 - level * 2}%)`
  root.style.setProperty('--eye-protection-filter', filterValue)
  root.classList.add('eye-protection')
}

const removeEyeProtection = () => {
  const root = document.documentElement
  root.classList.remove('eye-protection')
  root.style.removeProperty('--eye-protection-filter')
}

const setupAutoEyeProtection = () => {
  // 设置定时器，在指定时间自动开启/关闭护眼模式
  const checkTime = () => {
    const now = new Date()
    const hour = now.getHours()

    if ((hour >= 18 || hour < 8) && !interfaceSettings.eyeProtection) {
      interfaceSettings.eyeProtection = true
      applyEyeProtection()
    } else if (hour >= 8 && hour < 18 && interfaceSettings.eyeProtection) {
      interfaceSettings.eyeProtection = false
      removeEyeProtection()
    }
  }

  // 立即检查一次
  checkTime()

  // 每小时检查一次
  setInterval(checkTime, 60 * 60 * 1000)
}

const clearAutoEyeProtection = () => {
  // 清除自动护眼定时器（实际项目中需要保存定时器ID）
  console.log('清除自动护眼定时器')
}

const formatEyeProtectionTooltip = (value) => {
  const levels = ['很轻', '轻度', '中度', '重度', '很重']
  return levels[value - 1] || '中度'
}

const getEyeProtectionLevelText = () => {
  return formatEyeProtectionTooltip(interfaceSettings.eyeProtectionLevel)
}





// 服务区域管理
const handleAddServiceArea = () => {
  editingAreaIndex.value = -1
  resetAreaForm()
  areaDialogVisible.value = true
}

const editServiceArea = (index) => {
  editingAreaIndex.value = index
  const area = serviceAreas.value[index]
  areaForm.name = area.name
  areaForm.description = area.description
  areaForm.radius = area.radius
  areaDialogVisible.value = true
}

const removeServiceArea = async (index) => {
  try {
    await ElMessageBox.confirm('确认删除此服务区域？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const area = serviceAreas.value[index]
    if (area.id) {
      // 如果有ID，调用API删除
      const response = await deleteServiceArea(area.id)
      if (response.code === 200) {
        serviceAreas.value.splice(index, 1)
        ElMessage.success('服务区域已删除')
      } else {
        throw new Error(response.message || '删除服务区域失败')
      }
    } else {
      // 如果没有ID，直接从本地删除
      serviceAreas.value.splice(index, 1)
      ElMessage.success('服务区域已删除')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除服务区域失败:', error)
      ElMessage.error(error.message || '删除失败')
    }
  }
}

const resetAreaForm = () => {
  if (areaFormRef.value) {
    areaFormRef.value.resetFields()
  }
  areaForm.name = ''
  areaForm.description = ''
  areaForm.radius = 3
}

const saveServiceArea = async () => {
  if (!areaFormRef.value) return

  await areaFormRef.value.validate(async (valid) => {
    if (valid) {
      const areaData = {
        name: areaForm.name,
        description: areaForm.description,
        radius: areaForm.radius
      }

      // 验证服务区域数据
      const validation = validateServiceArea(areaData)
      if (!validation.valid) {
        ElMessage.error(validation.message)
        return
      }

      try {
        if (editingAreaIndex.value === -1) {
          // 添加新区域
          const response = await addServiceArea(areaData)
          if (response.code === 200) {
            serviceAreas.value.push(response.data || areaData)
            ElMessage.success('服务区域已添加')
          } else {
            throw new Error(response.message || '添加服务区域失败')
          }
        } else {
          // 更新现有区域
          const area = serviceAreas.value[editingAreaIndex.value]
          if (area.id) {
            const response = await updateServiceArea(area.id, areaData)
            if (response.code === 200) {
              serviceAreas.value[editingAreaIndex.value] = { ...area, ...areaData }
              ElMessage.success('服务区域已更新')
            } else {
              throw new Error(response.message || '更新服务区域失败')
            }
          } else {
            serviceAreas.value[editingAreaIndex.value] = areaData
            ElMessage.success('服务区域已更新')
          }
        }

        areaDialogVisible.value = false
        resetAreaForm()
      } catch (error) {
        console.error('保存服务区域失败:', error)
        ElMessage.error(error.message || '保存失败')
      }
    }
  })
}

// 保存所有设置
const saveAllSettings = async () => {
  try {
    saving.value = true

    // 验证设置数据
    const settingsData = {
      businessSettings: {
        isOpen: businessSettings.isOpen,
        maxDistance: businessSettings.maxDistance,
        freeDeliveryDistance: businessSettings.freeDeliveryDistance,
        deliveryFeePerKm: businessSettings.deliveryFeePerKm,
        replyTimeLimit: businessSettings.replyTimeLimit,
        workingHours: workingTimeRange.value
      },
      riskSettings: {
        refundRateThreshold: riskSettings.refundRateThreshold,
        goodReviewThreshold: riskSettings.goodReviewThreshold,
        responseTimeThreshold: riskSettings.responseTimeThreshold,
        enableRiskAlert: riskSettings.enableRiskAlert
      },
      notificationSettings: {
        newOrder: notificationSettings.newOrder,
        customerReview: notificationSettings.customerReview,
        financeChange: notificationSettings.financeChange,
        systemMaintenance: notificationSettings.systemMaintenance,
        methods: notificationSettings.methods
      },
      interfaceSettings: interfaceSettings
    }

    // 验证设置
    const validation = await validateSettings(settingsData)
    if (validation.code !== 200) {
      ElMessage.error(validation.message || '设置验证失败')
      return
    }

    // 分别保存各类设置
    const promises = [
      updateBusinessSettings(settingsData.businessSettings),
      updateRiskSettings(settingsData.riskSettings),
      updateNotificationSettings(settingsData.notificationSettings),
      updateInterfaceSettings(settingsData.interfaceSettings)
    ]

    const results = await Promise.allSettled(promises)

    let hasError = false
    results.forEach((result, index) => {
      if (result.status === 'rejected') {
        hasError = true
        console.error(`保存设置失败 (${index}):`, result.reason)
      }
    })

    if (!hasError) {
      // 保存界面设置到本地存储
      localStorage.setItem('merchant-interface-settings', JSON.stringify(interfaceSettings))
      ElMessage.success('所有设置已保存')
    } else {
      // 部分保存失败
      localStorage.setItem('merchant-interface-settings', JSON.stringify(interfaceSettings))
      ElMessage.warning('部分设置保存失败，界面设置已保存到本地')
    }
  } catch (error) {
    console.error('保存设置失败:', error)
    ElMessage.error(error.message || '保存设置失败')

    // 如果API失败，仍然保存界面设置到本地
    localStorage.setItem('merchant-interface-settings', JSON.stringify(interfaceSettings))
    ElMessage.warning('界面设置已保存到本地，业务设置保存失败')
  } finally {
    saving.value = false
  }
}

// 重置所有设置
const resetAllSettings = async () => {
  try {
    await ElMessageBox.confirm('确认重置所有设置为默认值？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await resetSettingsToDefault()
    if (response.code === 200) {
      // 重置为默认值
      Object.assign(businessSettings, {
        isOpen: false,
        maxDistance: 5,
        freeDeliveryDistance: 3,
        deliveryFeePerKm: 2,
        replyTimeLimit: 5
      })

      Object.assign(riskSettings, {
        refundRateThreshold: 15,
        goodReviewThreshold: 80,
        responseTimeThreshold: 3,
        enableRiskAlert: true
      })

      Object.assign(notificationSettings, {
        newOrder: true,
        customerReview: true,
        financeChange: true,
        systemMaintenance: true,
        methods: ['app', 'sms']
      })

      Object.assign(interfaceSettings, {
        theme: THEME_MODES.LIGHT,
        eyeProtection: false,
        eyeProtectionLevel: 3,
        autoEyeProtection: false
      })

      serviceAreas.value = []

      // 清除本地存储的界面设置
      localStorage.removeItem('merchant-interface-settings')

      ElMessage.success('所有设置已重置为默认值')
    } else {
      throw new Error(response.message || '重置设置失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('重置设置失败:', error)
      ElMessage.error(error.message || '重置设置失败')
    }
  }
}



// 页面初始化
onMounted(async () => {
  console.log('设置页面已加载')

  try {
    // 并行加载所有设置数据
    await Promise.all([
      getBusinessSettingsData(),
      getRiskSettingsData(),
      getNotificationSettingsData(),
      getInterfaceSettingsData(),
      getServiceAreasData()
    ])

    // 应用界面设置
    applyTheme(interfaceSettings.theme)
    if (interfaceSettings.eyeProtection) {
      applyEyeProtection()
    }
    if (interfaceSettings.autoEyeProtection) {
      setupAutoEyeProtection()
    }

    console.log('✅ 设置管理数据加载完成')
  } catch (error) {
    console.error('❌ 设置管理数据加载失败:', error)
    ElMessage.error('页面数据加载失败，请刷新重试')

    // 恢复界面设置作为备用
    const savedSettings = localStorage.getItem('merchant-interface-settings')
    if (savedSettings) {
      try {
        const settings = JSON.parse(savedSettings)
        Object.assign(interfaceSettings, settings)
        applyTheme(interfaceSettings.theme)
        if (interfaceSettings.eyeProtection) {
          applyEyeProtection()
        }
        if (interfaceSettings.autoEyeProtection) {
          setupAutoEyeProtection()
        }
      } catch (e) {
        console.error('恢复界面设置失败:', e)
      }
    }
  }
})
</script>

<style scoped>
.settings-management {
  padding: 20px;
}

.settings-card {
  border-radius: 8px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.setting-desc {
  font-size: 12px;
  color: #6b7280;
  margin-top: 5px;
}

.delivery-fee-section {
  .fee-item {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
    gap: 10px;

    .fee-label {
      min-width: 120px;
      font-size: 14px;
      color: #374151;
    }

    .fee-unit {
      font-size: 14px;
      color: #6b7280;
      margin-left: 5px;
    }
  }

  .fee-example {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 12px;
    background: #eff6ff;
    border-radius: 6px;
    border-left: 4px solid #3b82f6;
    margin-top: 10px;

    .el-icon {
      color: #3b82f6;
      font-size: 16px;
    }

    span {
      font-size: 13px;
      color: #1e40af;
      line-height: 1.4;
    }
  }
}

.risk-settings {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.risk-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.risk-item span {
  font-size: 14px;
  color: #374151;
}

.service-areas {
  min-height: 200px;
}

.area-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  margin-bottom: 10px;
}

.area-info {
  flex: 1;
}

.area-name {
  font-size: 16px;
  font-weight: 500;
  color: #1f2937;
  margin-bottom: 5px;
}

.area-desc {
  font-size: 14px;
  color: #6b7280;
  margin-bottom: 3px;
}

.area-range {
  font-size: 12px;
  color: #9ca3af;
}

.area-actions {
  display: flex;
  gap: 10px;
}

.empty-areas {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 150px;
}

.save-actions {
  margin-top: 30px;
  text-align: center;
}

.save-actions .el-button {
  margin: 0 10px;
}

:deep(.el-card__header) {
  background: #fafbfc;
  border-bottom: 1px solid #e5e7eb;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-slider__runway) {
  margin: 16px 0;
}

:deep(.el-checkbox-group) {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

:deep(.el-switch) {
  --el-switch-on-color: #67c23a;
}

/* 主题选择器样式 */
.theme-selector {
  .theme-options {
    display: flex;
    gap: 20px;
    margin-bottom: 16px;
  }

  .theme-option {
    flex: 1;
    cursor: pointer;
    border: 2px solid #e5e7eb;
    border-radius: 12px;
    padding: 16px;
    transition: all 0.3s ease;

    &:hover {
      border-color: #3b82f6;
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(59, 130, 246, 0.1);
    }

    &.active {
      border-color: #3b82f6;
      background: #eff6ff;
    }
  }

  .theme-preview {
    width: 100%;
    height: 80px;
    border-radius: 8px;
    margin-bottom: 12px;
    overflow: hidden;

    .preview-header {
      height: 20px;
      width: 100%;
    }

    .preview-content {
      display: flex;
      height: 60px;

      .preview-sidebar {
        width: 30%;
        height: 100%;
      }

      .preview-main {
        flex: 1;
        height: 100%;
      }
    }

    &.light-preview {
      background: #f8fafc;

      .preview-header {
        background: #ffffff;
        border-bottom: 1px solid #e5e7eb;
      }

      .preview-sidebar {
        background: #f1f5f9;
      }

      .preview-main {
        background: #ffffff;
      }
    }

    &.dark-preview {
      background: #1f2937;

      .preview-header {
        background: #374151;
        border-bottom: 1px solid #4b5563;
      }

      .preview-sidebar {
        background: #111827;
      }

      .preview-main {
        background: #1f2937;
      }
    }

    &.auto-preview {
      background: linear-gradient(90deg, #f8fafc 50%, #1f2937 50%);

      .preview-header {
        background: linear-gradient(90deg, #ffffff 50%, #374151 50%);
      }

      .preview-sidebar {
        background: linear-gradient(90deg, #f1f5f9 50%, #111827 50%);
      }

      .preview-main {
        background: linear-gradient(90deg, #ffffff 50%, #1f2937 50%);
      }
    }
  }

  .theme-name {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    font-size: 14px;
    font-weight: 500;
    color: #374151;
  }

  .theme-description {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 12px 16px;
    background: #f0f9ff;
    border: 1px solid #e0f2fe;
    border-radius: 8px;
    font-size: 13px;
    color: #0369a1;

    .el-icon {
      color: #0284c7;
    }
  }
}

/* 护眼设置样式 */
.eye-protection-settings {
  .setting-item {
    margin-bottom: 12px;
  }

  .setting-desc {
    font-size: 12px;
    color: #6b7280;
    margin-bottom: 16px;
  }

  .eye-protection-options {
    margin-top: 16px;
    padding: 16px;
    background: #f8fafc;
    border-radius: 8px;
    border: 1px solid #e5e7eb;

    .option-item {
      display: flex;
      align-items: center;
      margin-bottom: 12px;

      &:last-child {
        margin-bottom: 0;
      }

      .option-label {
        min-width: 80px;
        font-size: 14px;
        color: #374151;
        margin-right: 12px;
      }

      .option-value {
        margin-left: 12px;
        font-size: 12px;
        color: #6b7280;
      }

      .option-desc {
        margin-left: 12px;
        font-size: 12px;
        color: #6b7280;
      }
    }
  }
}

/* 全局主题样式 */
:root {
  --base-font-size: 14px;
}

.dark-theme {
  --bg-color: #1f2937;
  --text-color: #f9fafb;
  --border-color: #374151;
  --card-bg: #374151;
}

.light-theme {
  --bg-color: #f8fafc;
  --text-color: #1f2937;
  --border-color: #e5e7eb;
  --card-bg: #ffffff;
}

.eye-protection {
  filter: var(--eye-protection-filter, sepia(30%) saturate(85%) brightness(96%));
}

.font-size-small {
  font-size: 12px;
}

.font-size-medium {
  font-size: 14px;
}

.font-size-large {
  font-size: 16px;
}


</style>
